package com.itheima.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName ="loginFilter" ,urlPatterns = "/*")
@Slf4j
public class LoginFilter implements Filter {
private  static AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();

        String[] urls = {
                "/member/login.do",
                "/member.html",
                "/login.html",
                "/css/**",
                "/img/**",
                "/js/**",
                "/fonts/**",
                "/plugins/**",
                "/pages/login.html",
                "/pages/index.html",
                "/validateCode/send4Login.do"

        };
//如果在请求路径在放行集合中就对该请求进行放行
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if(match){
                //放行
                filterChain.doFilter(request,response);
                return;
            }
        }
        //不在放行请求中的请求路径，要根据是否登录进行判断是需要跳转到登录页面还是放行
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("telephoe");
        if(null==username){
            log.error("拦截到请求:{}",requestURI);
            response.sendRedirect("/pages/login.html");
        }
        filterChain.doFilter(request,response);
        return;
    }
}
